<template>
<div class="boxs">
  <!-- 查询-展示表格页面 -->
  <el-card shadow="never" class="el-cards">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item
        v-for="(item, index) in dataSet.queryBox"
        :label="item.label"
        :key="index"
      >
        <el-date-picker
            :style="{ width: '180px', marginLeft: index !== 0 ? '-25px' : '0px' }"
          v-if="item.type === 'picker'"
          clearable
          v-model="formInline[$convertHump(item.model)]"
          type="date"
          placeholder="请选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
        <el-input
          v-if="item.type === 'input'"
          :style="{ width: item.width ? item.width + 'px' : '180px', marginLeft: index !== 0 ? '-25px' : '0px' }"
          :type="item.inputType? item.inputType : ''"
          v-model="formInline[$convertHump(item.model)]"
          :placeholder="item.placeholder"
          clearable
        />
        <el-select
          v-if="item.type === 'select'"
          :style="{ width: '150px', marginLeft: index !== 0 ? '-25px' : '0px' }"
          v-model="formInline[$convertHump(item.model)]"
          :placeholder="item.placeholder"
          clearable
        >
          <el-option
            v-for="(data, index) in item.options"
            :label="data.label"
            :value="data.value"
            :key="index"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: -20px">
        <el-button size="default" type="primary" icon="Search" @click="onSubmit">
          查询</el-button
        >
        <el-button size="default" type="info" @click="reset" icon="Refresh"> 重置</el-button>
        <el-button
          type="warning"
          @click="print"
          v-if="showprint && printUrl !== ''"
        >
          <i class="iconfont icon-daochu"></i>
          导出</el-button
        >
        <el-button size="small"
          v-for="(data, index) in queryBtn"
          :key="index"
          :type="data.type"
          @click="$emit(data.click)"
          :color="data?.color ?? ''"
          :disabled="data.disabled"
          :icon="data.icon"
        >
          {{ data.name }}
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card v-if="tnQueryTop.length"
           v-loading="loading"
           element-loading-text="拼命加载中..."
           :element-loading-spinner="svg"
           element-loading-svg-view-box="-10, -10, 50, 50"
           element-loading-background="rgba(122, 122, 122, 0.8)"
           shadow="never">
    <el-button
      v-for="(data, index) in tnQueryTop"
      :key="index"
      size="small"
      @click="$emit(data.click, xmList)"
      :type="data.type"
    >
      <i :class="`iconfont icon-${data.icon}`"></i>
      {{ data.name }}
    </el-button>
    <el-table
      ref="multipleTableRef"
      :data="dataSet.tableData.rows"
      @selection-change="selectionChange"
      stripe style="width: 100%;margin-top: 10px"
      border="border">
      <template #empty>
        <el-empty :image-size="150"></el-empty>
      </template>
      <el-table-column type="selection" width="60"/>
      <el-table-column
        v-for="(item,index) in dataSet.tableList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width?? 'auto'"
        show-overflow-tooltip
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-for="(item,index) in dataSet.tableListStutas"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width?? 'auto'"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          <el-tag
            :type="props.getStatusColor(scope.row.statuss)"
            disable-transitions
          >{{ scope.row.statuss }}</el-tag>
        </template>
      </el-table-column>
        <el-table-column
        v-for="(item,index) in dataSet.tableListImages"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width?? 'auto'"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
            <el-image @click="dogImage(scope.row.imgUrl)" :src="scope.row.imgUrl" />
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item,index) in dataSet.tableListSubmit"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :width="item.width?? 'auto'"
        show-overflow-tooltip
        align="center"
      >
        <template #default="scope">
          <el-tag
            :type="props.getSubmitColor(scope.row.isSubmit)"
            disable-transitions
          >{{ props.getStatusText(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        :width="dataSet.operationBtns.length?(dataSet.operationBtns.length - roleLength) * 80 : 'auto'"
        align="center"
        v-if="dataSet?.operationBtns?.length ?? false"
        >
        <template #default="scope">
          <span v-for="(btn, index) in dataSet.operationBtns" :key="index">
            <el-button
              v-if="btn.click !== 'deleteId' && btn.click !== 'resetPassword' && (!btn.role)"
              :type="btn.type? btn.type : 'primary'"
              :size="btn.size? btn.size : 'small'"
              :icon="btn.icon"
              text
              :disabled="btn.disabled? btn.disabled : false"
              @click="$emit(btn.click, scope.row, scope.$index)"
            >
              {{ btn.name }}
            </el-button>
            <el-button
              v-else-if="btn.role===true && userData.id===scope.row.userId && btn.click !== 'deleteId' && btn.click !== 'resetPassword'"
              :type="btn.type? btn.type : 'primary'"
              :size="btn.size? btn.size : 'small'"
              :icon="btn.icon"
              text
              :disabled="btn.disabled? btn.disabled : false"
              @click="$emit(btn.click, scope.row, scope.$index)"
            >
              {{ btn.name }}
            </el-button>
            <el-popconfirm v-else-if="(btn.click === 'deleteId' || btn.click ==='resetPassword')&&(btn.role===true && userData.id===scope.row.userId)"
                           :title="btn.click ==='deleteId'?'确定从列表中移除吗？':'确定重置密码吗？'"
                           @cancel="cloneDelect(btn.click)"
                           @confirm="$emit(btn.click, scope.row)">
              <template #reference>
                <el-button :type="btn.type? btn.type : 'primary'"
                           :size="btn.size? btn.size : 'small'"
                           :icon="btn.icon"
                           :disabled="btn.disabled? btn.disabled : false" text>
                  {{ btn.name }}</el-button>
              </template>
              </el-popconfirm>
              <el-popconfirm v-else-if="(btn.click === 'deleteId' || btn.click ==='resetPassword') && (!btn.role)"
                           :title="btn.click ==='deleteId'?'确定从列表中移除吗？':'确定重置密码吗？'"
                           @cancel="cloneDelect(btn.click)"
                           @confirm="$emit(btn.click, scope.row)">
              <template #reference>
                <el-button :type="btn.type? btn.type : 'primary'"
                           :size="btn.size? btn.size : 'small'"
                           :icon="btn.icon"
                           :disabled="btn.disabled? btn.disabled : false" text>
                  {{ btn.name }}</el-button>
              </template>
            </el-popconfirm>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div style="margin-top: 10px;display: flex;justify-content: flex-end">
      <el-config-provider :locale="zhCn">
        <el-pagination
          v-model:current-page="formInline.pageNum"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          size="default"
          background="true"
          layout="total, sizes, prev, pager, next"
          :total="dataSet.tableData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-config-provider>
    </div>
  </el-card>
    <el-dialog class="dialog" width="750" v-model="dialogImageVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>
</div>
</template>

<script setup lang="ts">
import zhCn from "element-plus/es/locale/lang/zh-cn";
import {ElConfigProvider, ElMessage} from "element-plus";
import {useUserStore} from "@/pinia/stores/user.ts";
let formInline = reactive({
  pageNum: 1,
  pageSize: 10,
});
const props = defineProps({
  dataSet: {
    default: {}
  },
  getStatusColor: {
    type: Function,
    required: false
  },
  getSubmitColor: {
    type: Function,
    required: false
  },
  getStatusText: {
    type: Function,
    required: false
  },
  loading: {
    type: Boolean,
    default: false
  }
})
const userData = useUserStore().userInfo
const loading = ref(props.loading)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>`
const dialogImageVisible = ref(false)
const dialogImageUrl = ref('')
const cloneDelect = (data) => {
  ElMessage.info(data === 'deleteId' ? '已取消删除':'已取消重置密码')
}
const { tnQueryTop = [], queryBtn = [] } = props.dataSet;
const emit = defineEmits(["userExport", "userEdit","userBatchDelete", "selectSubmit", "resetSubmit", "handleChange"])
function $convertHump(str: string): string {
  return str.replace(/(_\w)/g, (match) => {
    return match[1].toUpperCase();
  });
}
const onSubmit = () => {
  emit('selectSubmit', formInline)
}
// 放大图片
const dogImage = (url) => {
    dialogImageVisible.value = true
    dialogImageUrl.value = url
}

const reset = () => {
  // 仅重置非分页属性，保留 `pageNum` 和 `pageSize`
  for (const key in formInline) {
    if (key !== "pageNum" && key !== "pageSize") {
      delete formInline[key]; // 清空其他值
    }
  }
  emit('resetSubmit', formInline)
}
// 每一页显示多少条
const handleSizeChange = (val) => {
  formInline.pageSize = val
  onSubmit();
}
// 第几页
const handleCurrentChange = (val) => {
  formInline.pageNum = val
  onSubmit();
}
let changeData = reactive([])
const selectionChange = (val) => {
  changeData = val
  emit('handleChange', changeData)
}
const multipleTableRef = ref(null);
defineExpose({
  clearSelection: () => {
    multipleTableRef.value?.clearSelection();
  },
});
watch(() => props.loading, (newVal) => {
  loading.value = newVal;
})
// 计算满足 btn.role 为 true 且 btn.userId 等于 scope.row.userId 的按钮个数
const roleLength = ref(0);
const filteredButtons = (row) => {
  roleLength.value =  props.dataSet.operationBtns.filter(btn => btn.role===true && userData.id !== row.userId).length;
};
// 监听表格数据的变化并调用 filteredButtons 方法
watch(() => props.dataSet.tableData.rows, (rows) => {
  rows.forEach(row => filteredButtons(row));
}, { immediate: true });
</script>
<style scoped lang="scss">
.boxs{
  width: 98%;
  margin: 0 auto;
  padding: 5px;
}
.table-data{
  padding: 10px;
  margin-top: 10px;
}
.el-cards{
  // 内容垂直居中，靠右显示
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
</style>
